package com.lry.crawlers.fiction.pipeline;

import com.jnewbie.JHtml;
import com.jnewbie.request.JPage;
import com.jnewbie.request.JParam;
import com.lry.crawlers.fiction.entity.Fiction;
import com.lry.crawlers.fiction.entity.FictionChapter;
import com.lry.crawlers.fiction.entity.FictionUpdate;
import com.lry.crawlers.fiction.service.FictionChapterService;
import com.lry.crawlers.fiction.service.FictionService;
import com.lry.crawlers.fiction.service.FictionUpdateService;
import com.lry.crawlers.information.service.InformationService;
import com.lry.crawlers.message.entity.Message;
import com.lry.crawlers.message.service.MessageService;
import com.lry.crawlers.util.StringTr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class FictionPipeline {
    public static Map<String,Object> cmap = new HashMap<>();
    @Autowired
    FictionService fictionService;
    @Autowired
    FictionChapterService fictionChapterService;
    @Autowired
    FictionUpdateService fictionUpdateService;
    @Autowired
    MessageService messageService;
    @Autowired
    InformationService informationService;
    @Value("${lry.web-url}")
    private String url;



    public boolean process(Map<String,Object> map) {

        //判断数据是否不为空
        if(map!= null) {
            //判断数据类型
            if (map.get("key").equals("fictionChapter")){
                Boolean is = fiction(map);
                if(is) {
                    chapter(map);
                }else {
                    return false;
                }
            }else if(map.get("key").equals("chapter")){
                chapter(map);
            }else if(map.get("key").equals("content")){
                content(map);
            }
        }
        return true;
    }
    //处理小说搜索
    public Boolean fiction(Map<String,Object> map) {
        Fiction fiction = null;
        String title = (String)  map.get("title");
        String descs = (String)  map.get("descs");
        String author = (String)  map.get("author");
        String fictionType =(String)  map.get("fictionType");
        String cover = (String)  map.get("cover");
        try {
            //提交封面到web端
            JHtml jHtml = new JHtml();
            jHtml.setTimeOut(10000);
            JParam jParam = new JParam();
            jParam.add("url", cover);
            jParam.add("ftitle",StringTr.TR(title));
            jParam.add("ititle",StringTr.TR(title)+".jpg");
            JPage post = jHtml.setParam(jParam).post(url+"/fiction/creation");
            int i = 0;
            while (!(post.getContent()!=null ? post.getContent().contains("成功") : false) && i<3){
                Thread.sleep(2000);
                post = jHtml.setParam(jParam).post(url+"/fiction/creation");
                i++;
            }
            if(post.getContent()!=null ? post.getContent().contains("成功") : false){
                cover = StringTr.TR(title)+"/" + StringTr.TR(title) + ".jpg";
            }else {
                cover = "defalult.jpg";
            }
        } catch (Exception e) {
            e.printStackTrace();
            cover = "defalult.jpg";
        }
        String updateTime = (String)  map.get("updateTime");
        String fictionId = (String) map.get("fictionId");

        Integer id = (Integer) map.get("id");
        fiction = new Fiction();
        fiction.setTitle(title.trim());
        fiction.setAuthor(author.trim());
        fiction.setCreationTime(new Date());
        fiction.setDescs(descs.trim());
        fiction.setFictionId(fictionId);
        fiction.setFictionType(fictionType.trim());
        fiction.setCover(cover);
        fiction.setFictionVariableId(id);
        fiction.setUpdateTime(updateTime);

        try {
            //添加到mysql
            int i= fictionService.setFiction(fiction);
            if(i==0){
                messageService.setMessage(new Message("mysql小说入库失败,fictionId:"+fictionId,new Date()));
            }else{
                FictionUpdate fictionUpdatec = new FictionUpdate();
                fictionUpdatec.setFictionId(fictionId);
                fictionUpdatec.setFictionVariableId(id);
                fictionUpdatec.setUpdateTime((String) map.get("updateTime"));
                String updateUrl = (String) map.get("updateUrl");
                updateUrl = "/" + updateUrl.split("/", 4)[3];
                fictionUpdatec.setFictionUrl(updateUrl);
                fictionUpdatec.setChapterNum(0);
                FictionUpdate fictionUpdate = fictionUpdateService.getFictionUpdate(fictionId);
                try {
                    if (fictionUpdate == null) {
                        fictionUpdateService.setFictionUpdate(fictionUpdatec);
                    }
                }catch(Exception e){
                    StringWriter sw = new StringWriter();
                    e.printStackTrace(new PrintWriter(sw,true));
                    String infomsg = sw.toString();
                    messageService.setMessage(new Message("小说更新表入库失败,fictionId:"+fictionId+" .Extends："+infomsg,new Date()));
                }
                return true;
            }
        }catch (DuplicateKeyException e){
        }catch (Exception e){
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw,true));
            String infomsg = sw.toString();
            messageService.setMessage(new Message("小说入库失败,fictionId:"+fictionId+" .Extends："+infomsg,new Date()));
        }
        return false;
    }


    //处理小说章节
    public void chapter(Map<String,Object> map){
        FictionChapter fictionChapter = null;
        String title = (String) map.get("title");
        List<String> chapterTitle = (List<String>) map.get("chapterTitle");
        List<String> chapterId = (List<String>) map.get("chapterId");
        String fictionId = (String) map.get("fictionId");
        List<Integer> sortt = map.get("sortt") !=null ? (List<Integer>) map.get("sortt") : null;
        for (int i =0;i<chapterId.size();i++) {
            fictionChapter = new FictionChapter();
            fictionChapter.setChapterId(chapterId.get(i));
            fictionChapter.setChapterPath(StringTr.TR(title.trim())+"/"+StringTr.TR(chapterTitle.get(i).trim())+".txt");
            fictionChapter.setFictionId(fictionId);
            fictionChapter.setTitle(chapterTitle.get(i).trim());
            fictionChapter.setCreationTime(new Date());
            if(sortt!=null)
                fictionChapter.setSortt(sortt.get(i));
            else
                fictionChapter.setSortt(i);
            cmap.put(chapterId.get(i),fictionChapter);
        }
        try {
            if(map.get("key").equals("chapter")) {
                fictionService.setupdateTime(new Fiction(fictionId,(String) map.get("updateTime")));
                fictionUpdateService.setFictionUpdateUp(new FictionUpdate(fictionId, (String) map.get("updateTime")));
            }
        }catch (Exception e){}

    }
    //处理小说内容
    public void content(Map<String,Object> map){
        List<String> content = (List<String>) map.get("content");
        String chapterId = (String) map.get("chapterId");
        if(content.size()==0){
            content.add("章节异常，请联系管理员处理");
        }
        FictionChapter fictionChapter =(FictionChapter) cmap.get(chapterId);
        String chapterPath = fictionChapter.getChapterPath();
        String[] split = chapterPath.split("/");
        try {
            //上传内容到web端
            JHtml jHtml = new JHtml();
            JParam jParam = new JParam();
            jParam.add("content", content.toString());
            jParam.add("ftitle",split[0]);
            jParam.add("ctitle",split[1]);
            JPage post = jHtml.setParam(jParam).setRetryTime(10000).setTimeOut(10000).post(url+"/fictionContent/creation");

            int i = 0;
            while (!(post.getContent()!=null ? post.getContent().contains("成功") : false) && i<3){
                System.out.println(chapterPath+"：上传堵塞，休息一会...");
                Thread.sleep(5000);
                post = jHtml.post(url+"/fictionContent/creation");
                i++;
            }

            if(post.getContent()!=null ? post.getContent().contains("成功") : false){
                chapter(fictionChapter.getFictionId(),chapterId);
                String infId = (String) map.get("infId");
                String[] inf = infId.split("!!!");
                int o = informationService.updateCount(inf[0],inf[1]);
                if(o==0){
                    Thread.currentThread().interrupt();
                }
            }else {
                messageService.setMessage(new Message("小说内容上传失败,chapter:"+fictionChapter,new Date()));
            }

        }catch (DuplicateKeyException e){
        }catch (Exception e){
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw,true));
            String infomsg = sw.toString();
            messageService.setMessage(new Message("小说内容入库失败,chapter:"+fictionChapter+" .Extends："+infomsg,new Date()));
            e.printStackTrace();
        }
    }

    public void chapter(String fictionId,String chapterId){
        FictionChapter fictionChapter =(FictionChapter) cmap.remove(chapterId);

        try {
            int i = 0;
            try{
                //添加到mysql
                i = fictionChapterService.setFictionChapter(fictionChapter);
            }catch (DuplicateKeyException e){
                i = fictionChapterService.setFictionChapterUp(fictionChapter);
            }
            if(i==0){
                messageService.setMessage(new Message("mysql小说章节入库失败,chapter:"+fictionChapter,new Date()));
            }else {
                fictionUpdateService.setFictionUpdateAddNum(fictionId);
            }
        }catch (DuplicateKeyException e){
        }catch (Exception e){
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw,true));
            String infomsg = sw.toString();
            messageService.setMessage(new Message("小说章节入库失败,chapter:"+fictionChapter+" .Extends："+infomsg,new Date()));
        }
    }

}